package com.hz.filemanager.ui.file;

import android.view.MenuItem;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.hz.filemanager.R;
import com.hz.filemanager.ad.utils.AnalyticsUtils;
import com.hz.filemanager.model.DialogManager;
import com.hz.filemanager.model.file.FileManager;
import com.hz.filemanager.model.file.Video;
import com.hz.filemanager.model.file.VideoFolderBean;
import com.hz.filemanager.ui.base.BaseActivity;
import com.hz.filemanager.ui.file.adapter.VideoAdapter;
import com.hz.filemanager.utils.FileUtils;
import com.hz.filemanager.utils.ThreadManager;
import com.hz.filemanager.utils.Utils;
import com.kathline.library.util.ZFileUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class VideoActivity extends BaseActivity implements VideoAdapter.OnLongClickListener, View.OnClickListener, VideoAdapter.OnItemClickListener {

    private RecyclerView videoRv;
    private VideoAdapter videoAdapter;

    private List<VideoFolderBean> videoFolderBeans;
    private LinearLayout modifyLl;
    private SwipeRefreshLayout refreshLayout;
    private LinearLayout emptyLayout;
    private TextView renameTv;
    private TextView deleteTv;
    private CheckedTextView cbAllToolbar;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_video;
    }

    @Override
    protected void initView() {
        AnalyticsUtils.INSTANCE.logEvent("cksp");

        videoRv = findViewById(R.id.rv);
        toolbar = findViewById(R.id.toolbar);
        modifyLl = findViewById(R.id.modify_ll);
        refreshLayout = findViewById(R.id.refreshLayout);
        emptyLayout = findViewById(R.id.emptyLayout);

        renameTv = findViewById(R.id.rename_tv);
        deleteTv = findViewById(R.id.delete_tv);
        cbAllToolbar = (CheckedTextView) findViewById(R.id.cb_all_toolbar);

    }

    @Override
    protected void initEvent() {

        renameTv.setOnClickListener(this);
        deleteTv.setOnClickListener(this);

        toolbar.setTitle(getString(R.string.videos));
        refreshLayout.setEnabled(false);
        //refreshLayout.setColorSchemeColors();
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });

        cbAllToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cbAllToolbar.toggle();
                if (cbAllToolbar.isChecked()){
                    videoAdapter.checkAllOf(true);
                }else {
                    videoAdapter.checkAllOf(false);
                }
                checkState();
            }
        });

        videoAdapter = new VideoAdapter(this);
        videoAdapter.setOnLongClickListener(this);
        videoAdapter.setOnItemClickListener(this);
        videoRv.setLayoutManager(new LinearLayoutManager(this));
        videoRv.setAdapter(videoAdapter);
        getData();
    }

    private void getData() {
        refreshLayout.setRefreshing(true);
        ThreadManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                videoFolderBeans = FileManager.getInstance(Utils.getContext()).getVideosFolders();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (videoFolderBeans == null || videoFolderBeans.size() == 0) {
                            videoAdapter.clear();
                            emptyLayout.setVisibility(View.VISIBLE);
                        } else {
                            videoAdapter.getExpandGroupSet().add(videoFolderBeans.get(0));
                            videoAdapter.setDatas(videoFolderBeans);
                            videoRv.scrollToPosition(0);
                            emptyLayout.setVisibility(View.GONE);
                        }
                        refreshLayout.setRefreshing(false);
                    }
                });
            }
        });
    }

    @Override
    public void onLongClick(VideoFolderBean groupBean, Video video) {
        updateSelectMode(true);
        checkState();
    }

    @Override
    public void onClick(View view, VideoFolderBean groupBean, Video video) {
        if(videoAdapter.isSelectModel()){
            checkState();
        }else{
            //播放视频
            ZFileUtil.openFile(video.getPath(), view);
        }
    }

    private void updateSelectMode(boolean isSelectedMode) {
        if(isSelectedMode){
            modifyLl.setVisibility(View.VISIBLE);
            cbAllToolbar.setVisibility(View.VISIBLE);
            toolbar.setNavigationIcon(getDrawable(R.mipmap.cancle));
        }else{
            modifyLl.setVisibility(View.GONE);
            cbAllToolbar.setVisibility(View.GONE);
            toolbar.setNavigationIcon(getDrawable(R.mipmap.back));
        }
        videoAdapter.setSelectModel(isSelectedMode);
        videoAdapter.getSelectVideoList().clear();
        videoAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        if(videoAdapter.isSelectModel()){
            updateSelectMode(false);
        }else{
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                //选择状态下，点击左上角 x 取消选中模式
                //清空已选择数据 恢复勾选数据 导航重置为返回键
                if (videoAdapter.isSelectModel()) {
                    updateSelectMode(false);
                } else {
                    //非选择状态，结束
                    finish();
                }
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.rename_tv:

                final Video renameVideo = videoAdapter.getSelectVideoList().get(0);
                DialogManager.renameDialog(VideoActivity.this
                        , renameVideo.getPath()
                        , renameVideo.getName()
                        , new DialogManager.OnRenameListener() {
                            @Override
                            public void onSuccess(String newName, String newPath) {
                                updateSelectMode(false);
                                renameVideo.setName(newName);
                                renameVideo.setPath(newPath);
                                //更新数据
                                videoAdapter.notifyDataSetChanged();
                                //getData();
                               //showToast("rename success");
                            }

                            @Override
                            public void onFailed() {
                                showToast("Rename failure");
                            }
                        });
                break;
            case R.id.delete_tv:
                DialogManager.deleteFileDialog(VideoActivity.this, new DialogManager.OnDialogClickListener() {
                    @Override
                    public void onOKClick(Object data) {
                        //即将删除的文件路径
                        List<String> deleteFilePaths = new ArrayList<>();
                        //需要adapter更新的item位置
                        final Set<Integer> positions = new HashSet<>();

                        //遍历选中的数据
                        for (Video video : videoAdapter.getSelectVideoList()) {
                            //拿到当前数据的路径
                            final String beanPath = video.getPath();
                            //删除此文件
                            if(FileUtils.deleteFile(beanPath)){
                                deleteFilePaths.add(beanPath);
                            }
                        }
                        //showToast("delete success for "+deleteFilePaths.size()+" file");
                        //通知数据库更新已经删除的路径文件
                        notifyFileIsDeleted(deleteFilePaths);

                        updateSelectMode(false);
                        getData();
                    }
                });
                break;
        }
    }

    private void checkState() {

        if (videoAdapter.getSelectVideoList().size() == 1) {
            renameTv.setEnabled(true);
        } else {
            renameTv.setEnabled(false);
        }
        if (videoAdapter.getSelectVideoList().size() == 0) {
            deleteTv.setEnabled(false);
        } else {
            deleteTv.setEnabled(true);
        }
    }


}
